<template>
  <business-layout title='缺陷管理' custom-title>
    <template slot='header'>
      <div class='table-tab'>
        <a-tabs v-model='activeKey'>
          <a-tab-pane key='0' tab='待处理'>
          </a-tab-pane>
          <a-tab-pane key='1' tab='待归档'>
          </a-tab-pane>
          <a-tab-pane key='2' tab='已完成'>
          </a-tab-pane>
        </a-tabs>
      </div>

      <div class='table-operator'>
        <a-form :form='form' layout='inline' @submit='handleQueryData'>
          <a-form-item label=''>
            <a-date-picker
              v-model='queryParam.startTime'
              valueFormat='YYYY-MM-DD 00:00:00'
              format='YYYY-MM-DD 00:00:00'
              placeholder='请选择开始时间'
              :disabled-date='startDisabledDate'
            />
          </a-form-item>
          <a-form-item label=''>
            <a-date-picker
              v-model='queryParam.endTime'
              :disabled-date='endDisabledDate'
              format='YYYY-MM-DD 23:59:59'
              valueFormat='YYYY-MM-DD 23:59:59'
              placeholder='请选择结束时间'
            />
            <a-button type='primary' style='margin-left: 10px' html-type='submit'>
              <a-icon type='search' />
              查询
            </a-button>

            <a-button html-type='reset' @click='handleResetDate'>
              重置
            </a-button>
          </a-form-item>
          <a-form-item style='float: right'>
            <a-button style='margin-left: 10px' type='primary' icon='plus' @click='handleAdd'>新建</a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='key'
      :columns='columns'
      :data='loadData'
      :alert='false'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='desc' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='defectLevelDicId' slot-scope='text'>
        <span>{{ computedDefectLevel(text) }}</span>
      </span>
      <span slot='status' slot-scope='text'>
        <a-tag :color='text | filterStatusStyle'>{{ statusObj[text] }}</a-tag>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleView(record)'>查看详情</a>
          <template v-if='record.status === "1" && (username === record.currUser || usetType === "1")'>
            <a-divider type='vertical' />
            <a @click='handleEdit(record)'>编辑</a>
          </template>
          <template v-if='record.status === "1" &&  (username === record.currUser || usetType === "1")'>
            <a-divider type='vertical' />
            <a @click='handleSubmitDefect(record)'>处理</a>
          </template>
          <template v-if='record.status === "2" &&  (username === record.currUser || usetType === "1")'>
            <a-divider type='vertical' />
            <a @click='archiveDefectVisable(record)'>归档</a>
          </template>
          <template v-if='record.status === "1" &&  (username === record.currUser || usetType === "1")'>
            <a-divider type='vertical' />
            <a class='del-link' @click='handleCancelVisable(record)'>撤销</a>
          </template>
        </template>
      </span>
    </s-table>

    <create-form
      ref='createModal'
      :edit='edit'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <bug-defect
      ref='bug-defect'
      :visible='archiveVisable'
      :loading='archiveLoading'
      :model='mdl'
      @cancel='handleArchiveCancel'
      @ok='handleArchiveOk'
    />

    <guidang-model
      ref='guidang-model'
      :visible='guidangVisable'
      :loading='guidangLoading'
      :model='mdl'
      @cancel='guidangVisable = false'
      @ok='handleGuidangOk'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import GuidangModel from './modules/guidangModel.vue'
import {
  findToHandleDefect,
  findToArchiveDefect,
  findCompletedDefect,
  create,
  update,
  handleDefect,
  archiveDefect,
  cancelDefect
} from '@/api/defectManagement'
import { findDataDicInfoByType } from '@/api/dataDicInfo'
import BugDefect from './modules/bugDefect.vue'
import CreateForm from './modules/CreateWorkOrderForm.vue'
import { mapState } from 'vuex'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '缺陷编号',
    dataIndex: 'defectNo'
  },
  {
    title: '缺陷描述',
    dataIndex: 'desc',
    scopedSlots: { customRender: 'desc' }
  },
  {
    title: '缺陷等级',
    dataIndex: 'defectLevelDicId',
    scopedSlots: { customRender: 'defectLevelDicId' }
  },
  {
    title: '站点',
    dataIndex: 'station'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime'
  },
  {
    title: '当前处理人',
    dataIndex: 'currUser'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    BugDefect,
    GuidangModel
  },
  data() {
    this.columns = columns
    return {
      activeKey: '0',
      // create model
      visible: false,
      confirmLoading: false,
      archiveVisable: false,
      archiveLoading: false,
      guidangVisable: false,
      guidangLoading: false,
      form: this.$form.createForm(this),
      mdl: null,
      edit: true,
      // 高级搜索 展开/关闭
      advanced: false,
      defectId: '',
      // 查询参数
      queryParam: {},
      statusObj: {
        '1': '待处理',
        '2': '待归档',
        '3': '已完成',
        '4': '已撤销'
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return this.getDataFun(requestParameters)
      },
      selectedRowKeys: [],
      selectedRows: [],
      defectLevelDicList: []
    }
  },
  filters: {
    filterStatusStyle(val) {
      if (+val === 0) {
        return 'cyan'
      }
      if (+val === 1) {
        return 'pink'
      }
      if (+val === 2) {
        return 'green'
      }
      if (+val === 3) {
        return 'blue'
      }
    }
  },
  watch: {
    activeKey() {
      this.$refs.table.refresh()
    }
  },
  computed: {
    ...mapState({
      username: state => state.user.username,
      usetType: state => state.user.info.userType
    }),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    },
    getDataFun() {
      if (+this.activeKey === 0) {
        return findToHandleDefect
      }
      if (+this.activeKey === 1) {
        return findToArchiveDefect
      }
      if (+this.activeKey === 2) {
        return findCompletedDefect
      }
    }
  },
  mounted() {
  },
  created() {
    this.getLeavelDic()
    if (this.$route.query.mark) {
      this.activeKey = '1'
    }
  },
  methods: {
    archiveDefectVisable(value) {
      this.defectId = value.id
      this.guidangVisable = true
    },
    handleCancelVisable(value) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        async onOk() {
          cancelDefect({
            defectId: value.id
          }).then(res => {
            that.$message.success('更新成功！')
            that.$refs.table.refresh()
          })
        }
      })
    },
    handleSubmitDefect(value) {
      this.defectId = value.id
      this.archiveVisable = true
    },
    computedDefectLevel(val) {
      const resObj = this.defectLevelDicList.find(item => Number(item.key) === Number(val))
      if (resObj) {
        return resObj.label
      }
      return ''
    },
    getLeavelDic() {
      findDataDicInfoByType(14).then(res => {
        this.defectLevelDicList = res.map(item => {
          return {
            ...item,
            key: item.code,
            label: item.name
          }
        })
      })
    },
    startDisabledDate(startValue) {
      const endValue = this.queryParam.endTime
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > moment(endValue).valueOf()
    },
    endDisabledDate(endValue) {
      const startValue = this.queryParam.startTime
      if (!startValue || !endValue) {
        return false
      }
      return moment(startValue).valueOf() >= endValue.valueOf()
    },
    handleAdd() {
      this.$refs.createModal.imageUrl = null
      this.mdl = null
      this.edit = true
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.edit = true
      this.mdl = { ...record }
    },
    handleArchiveCancel() {
      this.archiveVisable = false
    },
    handleGuidangOk() {
      const form = this.$refs['guidang-model'].form
      form.validateFields((err, values) => {
        archiveDefect({
          defectId: this.defectId,
          ...values
        }).then(res => {
          this.$message.success('更新成功！')
          this.$refs.table.refresh()
          this.guidangVisable = false
          form.resetFields()
        })
      })
    },
    handleArchiveOk() {
      const form = this.$refs['bug-defect'].form
      this.archiveLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          handleDefect({
            defectId: this.defectId,
            ...values
          }).then(res => {
            if (res) {
              this.archiveVisable = false
              this.$message.success('更新成功！')
              this.archiveLoading = false
              this.$refs.table.refresh()
              form.resetFields()
            } else {
              this.$message.error('处理失败！')
            }
          }).finally(() => {
            this.archiveLoading = false
          })
        } else {
          this.archiveLoading = false
        }
      })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            update(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('更新成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            // 新增
            create(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleView(record) {
      this.visible = true
      this.edit = false
      this.mdl = { ...record }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        // this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleResetDate() {
      const form = this.form
      form.resetFields()
      this.queryParam = {}
      this.handleQueryData()
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>

